use tonic::{transport::Server, Request, Response, Status};
use resource::resource_manager_server::{ResourceManager, ResourceManagerServer};
use resource::{ResourceReply, ResourceRequest};

pub mod resource {
    tonic::include_proto!("resource");
}

#[derive(Debug, Default)]
pub struct ResourceManagerService;

#[tonic::async_trait]
impl ResourceManager for ResourceManagerService {
    async fn allocate(
        &self,
        request: Request<ResourceRequest>,
    ) -> Result<Response<ResourceReply>, Status> {
        let req = request.into_inner();
        println!(
            "[服务端] 分配请求 - 用户: {}, 资源: {:?}",
            req.client_id, req.resource_ids
        );

        Ok(Response::new(ResourceReply {
            success: true,
            message: format!("已为 {} 分配资源 {:?}", req.client_id, req.resource_ids),
        }))
    }

    async fn free(
        &self,
        request: Request<ResourceRequest>,
    ) -> Result<Response<ResourceReply>, Status> {
        let req = request.into_inner();
        println!(
            "[服务端] 释放请求 - 用户: {}, 资源: {:?}",
            req.client_id, req.resource_ids
        );

        Ok(Response::new(ResourceReply {
            success: true,
            message: format!("已为 {} 释放资源 {:?}", req.client_id, req.resource_ids),
        }))
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let addr = "[::1]:50051".parse()?;
    println!("服务端监听地址: {}", addr);

    let service = ResourceManagerService::default();

    Server::builder()
        .add_service(ResourceManagerServer::new(service))
        .serve(addr)
        .await?;

    Ok(())
}
